package com.example.demo.common.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token"); // 或从Cookie中获取
        if (token == null) {
            response.setStatus(401);
            return false;
        }

        // 从Redis查询Token有效性
        String userId = stringRedisTemplate.opsForValue().get("login_token_" + token);
        if (userId == null) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
}